from datetime import datetime
from sqlalchemy import select, desc, func
from sqlalchemy.orm import joinedload
from model.blog import BlogCategory, Blog
from model.user import GoldCoinsLog
from db.session import get_session



async def get_blog_category():
    """获取博客分类

    Returns:
        _type_: _description_
    """
    async with get_session() as db:
        stmt = select(BlogCategory).filter(BlogCategory.is_deleted == False)
        blog_type = await db.execute(stmt)
        return blog_type.scalars().all()
    

async def get_blog_by_category(blog_type_id: int, title: str | None = None):
    """根据分类获取博客列表

    Args:
        blog_type_id (int):分类id
        title (str | None, optional): 博客标题 模糊查询. Defaults to None.

    Returns:
        _type_: _description_
    """
    async with get_session() as db:
        if title:
            # .options(joinedload(Blog.category)) Pydantic查询外键数据时 避免 懒加载时会话关闭
            stmt = select(Blog).filter(Blog.category_id == blog_type_id, Blog.is_deleted == False, Blog.title.like(f"%{title}%")).order_by(desc(Blog.create_time)).options(joinedload(Blog.category), joinedload(Blog.user))
        else:
            stmt = select(Blog).filter(Blog.category_id == blog_type_id, Blog.is_deleted == False).order_by(desc(Blog.create_time)).options(joinedload(Blog.category), joinedload(Blog.user))
        blogs = await db.execute(stmt)
        return blogs.scalars().all()


async def get_blog_detail(blog_id: int):
    """查看详情

    Args:
        blog_id (int): 博客id

    Returns:
        _type_: _description_
    """
    async with get_session() as db:
        stmt =  select(Blog).filter(Blog.id == blog_id, Blog.is_deleted == False).options(joinedload(Blog.category), joinedload(Blog.user))
        blog = await db.execute(stmt)
        return blog.scalars().first()
    

async def get_today_blog_in_log(user_id: int, blog_id: int ):
    """如果博客今天看了今天不消耗

    Args:
        user_id (str): 用户id
    """
    async with get_session() as db:
        stmt = select(GoldCoinsLog).where(GoldCoinsLog.source_user_id == user_id,
                                          GoldCoinsLog.blog_id == blog_id, 
                                          func.date(GoldCoinsLog.create_time) == datetime.now().date())
        user = await db.execute(stmt)
        return user.scalars().first()